process.mixin(GLOBAL, require('sys'), require('./tools'), require('events'));

/** 
 *
 */
var EventSource = exports.EventSource = function(config) {
  EventEmitter.call(this);

  this.source = config.source;
  this.handler = config.handler;

  //Set properties
  //property(this,'id', config.id, true);
  this.id = config.id;
  property(this,'name', config.name);

};
process.inherits(EventSource, EventEmitter);

/**
 * Constructor
 */
var IntervalEventSource = exports.IntervalEventSource = function(config) {
  EventSource.call(this, config);

  property(this,'state', this.states.STOPPED);
  property(this,'runcount', 0);
  property(this,'interval', config.interval);
};
process.inherits(IntervalEventSource, EventSource);

/**
 * Define the possible states for this object
 */
IntervalEventSource.prototype.states = {
  STOPPED: 'stopped',
  STARTED: 'started',
  STOPPING: 'stopping',
  WAITING: 'waiting',
  RUNNING: 'running'
};

/**
 *
 */
IntervalEventSource.prototype.run = function() {
  if(this.state === this.states.WAITING || this.state === this.states.STARTED) {
    this.state = this.states.RUNNING;
    this.runcount += 1;

    var starttime = new Date().getTime();

    this.source(function(success, data) {

      if(data) {
        this.handler({
          createtime: new Date().getTime(),
          elapsedtime: new Date().getTime() - starttime,
          name: (success) ? 'data' : 'error',
          data: data
        });
      }

      if(this.state === this.states.STOPPING) {
        this.state = this.states.STOPPED;
      } else {
        this.state = this.states.WAITING;
      }

    }.bind(this));
  }
};

/**
 * Start the collector
 */
IntervalEventSource.prototype.start = function() {
  var id = null;

  if(this.interval) {
    id = setInterval(this.run.bind(this), this.interval * 1000);
    this.state = this.states.STARTED;

    //Return a function to stop the interval
    return function() {
      clearInterval(id);

      //Only change the state if we don't have any more pending results
      if(this.state === this.states.WAITING) {
        this.state = this.states.STOPPED;
      } else {
        this.state = this.states.STOPPING;
      }
    }.bind(this);
  } else {
    puts("ERROR: no interval defined!");
  }
};

